<template>
  <view v-if="visibleSync" class="cu-modal" :class="{ show: isShow, 'bottom-modal': mode == 'bottom' }"
    :style="{zIndex: zIndex}" @click.stop="onClickOverlay" @touchmove.stop.prevent>
    <view class="cu-dialog bg-white text-left" :style="[customStyle, style]" @click.stop>
      <view class="cuIcon-close btn-close" @click.stop="close" v-if="closeable && mode == 'center'"></view>
      <scroll-view scroll-y="true">
        <slot />
      </scroll-view>
    </view>
  </view>
</template>
<script>
export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'bottom'
    },
    closeable: {
      type: Boolean,
      default: false
    },
    closeOnClickOverlay: {
      type: Boolean,
      default: true
    },
    width: {
      type: [Number, String],
      default: null
    },
    height: {
      type: [Number, String],
      default: null
    },
    borderRadius: {
      type: [Number, String],
      default: null
    },
    // 用户自定义样式
    customStyle: {
      type: Object,
      default() {
        return {};
      }
    },
    zIndex: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      isShow: false,
      visibleSync: false,
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val) {
          //显示
          this.visibleSync = true
          this.$nextTick(() => {
            this.isShow = true
            this.$emit('open')
          })
        } else {
          //隐藏
          this.isShow = false
          setTimeout(() => {
            this.visibleSync = false
            this.$emit('close')
          }, 300);
        }
      },
    }
  },
  computed: {
    style() {
      let { width, height, borderRadius, mode } = this
      let data = {}
      if (height) {
        data.height = this.getUnitValue(height)
      }
      data.width = mode == 'center' ? 'auto' : ''
      if (width) {
        data.width = this.getUnitValue(width)
      }
      if (borderRadius) {
        borderRadius = this.getUnitValue(borderRadius)
        data.borderRadius = mode == 'bottom' ? `${borderRadius} ${borderRadius} 0 0` : borderRadius
        data.overflow = 'hidden'
      }
      return data
    }
  },
  methods: {
    close() {
      this.$emit('input', false)
    },
    onClickOverlay() {
      if (this.closeOnClickOverlay) {
        this.close()
      }
    },
    getUnitValue(val) {
      if (/(%|px|rpx|auto)$/.test(val)) {
        return val;
      } else {
        return val + 'rpx'
      }
    },
  },
}
</script>
<style scoped>
.btn-close {
  position: absolute;
  z-index: 1000;
  top: 30rpx;
  right: 30rpx;
  font-size: 38rpx;
  color: #909399;
}
</style>